package com.luyuan.crm.sale.web.provider;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.faces.model.SelectItem;

import org.springframework.stereotype.Component;

import com.luyuan.crm.member.model.MemberIntegral;
import com.luyuan.crm.promotion.Promotion;
import com.luyuan.crm.promotion.PromotionLimitedAmount;
import com.luyuan.crm.promotion.PromotionLimitedMemberLevel;
import com.luyuan.crm.promotion.PromotionLimitedPackage;
import com.luyuan.crm.promotion.PromotionService;
import com.luyuan.crm.sale.model.Order;
import com.luyuan.crm.sale.model.OrderProduct;
import com.ruijie.web.jsf.context.WizardScope;
import com.ruijie.web.jsf.provider.SelectItemsProvider;

@Component("promotionProvider")
public class PromotionProvider implements SelectItemsProvider {
    @Resource(name = "promotionService")
    private PromotionService promotionService;

    @Override
    public List<SelectItem> getSelectItems(Object... arg0) {
        MemberIntegral memberIntegral = (MemberIntegral) WizardScope.get("memberIntegral");
        Order order = (Order) WizardScope.get("order");
        List<OrderProduct> orderProducts = (List<OrderProduct>) WizardScope.get("orderProducts");

        List<Promotion> promotions = promotionService.findEffectivePromotion();
        List<SelectItem> items = new ArrayList<SelectItem>();
        for (Promotion promotion : promotions) {
            if (promotion.getLimited() instanceof PromotionLimitedMemberLevel) {
                PromotionLimitedMemberLevel limited = (PromotionLimitedMemberLevel) promotion.getLimited();
                if (limited.getMemberLevel().getMemberLevel() <= memberIntegral.getMemberLevel().getMemberLevel()) {
                    items.add(new SelectItem(promotion, promotion.getTheme()));
                }
            }
            else if (promotion.getLimited() instanceof PromotionLimitedPackage) {
                PromotionLimitedPackage limited = (PromotionLimitedPackage) promotion.getLimited();
                int count = 0;
                for (OrderProduct orderProduct : orderProducts) {
                    if (!orderProduct.isGift() && orderProduct.getExchangeIntegral() == 0) {
                        count += orderProduct.getCount();
                    }
                }
                if (limited.getPackingNumber() <= count) {
                    items.add(new SelectItem(promotion, promotion.getTheme()));
                }
            }
            else if (promotion.getLimited() instanceof PromotionLimitedAmount) {
                PromotionLimitedAmount limited = (PromotionLimitedAmount) promotion.getLimited();
                if (limited.getAmount() <= order.getOldAmount()) {
                    items.add(new SelectItem(promotion, promotion.getTheme()));
                }
            }
        }
        return items;
    }
}
